package com.sc.admin.core.mq.consumer;

import com.alibaba.fastjson.JSONObject;
import com.sc.admin.core.service.SysImportExportService;
import com.sc.common.dto.WebResponseDto;
import com.sc.common.entity.admin.importexport.SysImportExport;
import com.sc.common.entity.admin.importexport.SysImportExportSearch;
import com.sc.common.exception.BusinessException;
import com.sc.common.service.ExportExcelService;
import com.sc.common.util.MyStringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import java.util.Date;

/**
 * @author ：wust
 * @date ：Created in 2019/7/19 15:21
 * @description：
 * @version:
 */
@Component
@RabbitListener(
        containerFactory = "singleListenerContainer",
        bindings = @QueueBinding(
                value = @Queue(
                        value = "${spring.rabbitmq.exportexcel.queue.name}",
                        durable = "${spring.rabbitmq.exportexcel.queue.durable}"
                ),
                exchange = @Exchange(
                        value = "${spring.rabbitmq.exportexcel.exchange.name}",
                        durable = "${spring.rabbitmq.exportexcel.exchange.durable}",
                        type = "${spring.rabbitmq.exportexcel.exchange.type}",
                        ignoreDeclarationExceptions = "${spring.rabbitmq.exportexcel.exchange.ignoreDeclarationExceptions}"
                ),
                key = "${spring.rabbitmq.exportexcel.routing-key}"
        )
)
public class Consumer4ExportExcelQueue {
    static Logger logger = LogManager.getLogger(Consumer4ExportExcelQueue.class);

    @Autowired
    private ExportExcelService exportExcelServiceImpl;

    @Autowired
    private SysImportExportService sysImportExportServiceImpl;

    @Autowired
    private Environment environment;

    @RabbitHandler
    public void process(JSONObject jsonObject) {
        WebResponseDto responseDto = new WebResponseDto();

        String applicationName = jsonObject.getString("spring.application.name");
        String applicationName1 = environment.getProperty("spring.application.name");

        if(MyStringUtils.isBlank(applicationName)){
            throw new BusinessException("请指定目标服务名");
        }


        if(!applicationName.equals(applicationName1)){
            return;
        }

        try {
            this.before(jsonObject);
            responseDto = this.doExport(jsonObject);
        } catch (Exception e) {
            logger.error(e);
            responseDto.setFlag(WebResponseDto.INFO_ERROR);
            responseDto.setCode("A100504");
            if (MyStringUtils.isNotBlank(e.getMessage())) {
                int length = e.getMessage().length() >= 500 ? 500 : e.getMessage().length();
                responseDto.setMessage(e.getMessage().substring(0, length));
            } else {
                int length = e.toString().length() >= 500 ? 500 : e.toString().length();
                responseDto.setMessage("导出失败:" + e.toString().substring(0, length));
            }
        } finally {
            this.after(jsonObject, responseDto);
        }
    }


    /**
     * 导出前，记录初始状态和开始时间
     *
     * @param jsonObject
     */
    private void before(JSONObject jsonObject) {
        SysImportExport sysImportExport = jsonObject.getObject("sysImportExport", SysImportExport.class);

        SysImportExport importExportSearch = new SysImportExport();
        importExportSearch.setBatchNo(sysImportExport.getBatchNo());
        SysImportExport importExport = sysImportExportServiceImpl.selectOne(importExportSearch);
        if (importExport == null){
            sysImportExportServiceImpl.insert(sysImportExport);
        }
    }

    /**
     * 执行导出
     *
     * @param jsonObject
     */
    private WebResponseDto doExport(JSONObject jsonObject) {
        return exportExcelServiceImpl.export(jsonObject);
    }

    /**
     * 导出后，记录结果状态，并记录结束时间
     *
     * @param jsonObject
     * @param responseDto
     */
    private void after(JSONObject jsonObject, WebResponseDto responseDto) {
        SysImportExport sysImportExport = jsonObject.getObject("sysImportExport", SysImportExport.class);
        SysImportExportSearch condition = new SysImportExportSearch();
        condition.setBatchNo(sysImportExport.getBatchNo());
        SysImportExport sysImportExportUpdate = sysImportExportServiceImpl.selectOne(condition);

        if(!responseDto.isSuccess()){
            if (sysImportExportUpdate != null) {
                sysImportExportUpdate.setStatus(responseDto.getCode());
                sysImportExportUpdate.setEndTime(new Date());
                sysImportExportUpdate.setModifyTime(new Date());
                sysImportExportUpdate.setMsg(responseDto.getMessage());
                sysImportExportServiceImpl.updateByPrimaryKey(sysImportExportUpdate);
            }
        }else{
            JSONObject jsonObjectResponse = (JSONObject) responseDto.getObj();
            if (sysImportExportUpdate != null) {
                sysImportExportUpdate.setStatus(responseDto.getCode());
                sysImportExportUpdate.setEndTime(new Date());
                sysImportExportUpdate.setModifyTime(new Date());
                sysImportExportUpdate.setMsg(responseDto.getMessage());
                sysImportExportUpdate.setName(jsonObjectResponse.getString("name"));
                sysImportExportUpdate.setSize(jsonObjectResponse.getInteger("size"));
                sysImportExportUpdate.setFileId(jsonObjectResponse.getLong("fileId"));
                sysImportExportServiceImpl.updateByPrimaryKey(sysImportExportUpdate);
            }
        }
    }
}
